import router from './router'
import store from '@/store'
import iView from 'view-design'
import {Message } from 'view-design';
import {getToken, setTitle } from '@/libs/util'
import config from '@/config'
const { homeName } = config

const LOGIN_PAGE_NAME = 'login'
const allowList = ['login', 'register','forgetPass','resetResult','registerResult']
const loginRoutePath = '/login'
const otherRouter=[{
  path: "*",
  name: "error_404",
  meta: { hideInMenu: true,title: '404-页面不存在' },
  component: () => import("@/components/error-page/404.vue")
}]
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start() // start progress bar
  /* has token */
  const token = getToken()
  if (token) {
    if (to.name== LOGIN_PAGE_NAME) {
      next({ path: homeName })
      iView.LoadingBar.finish()
    }else{
      // check login user.roles is null
      if (store.state.user.access.length === 0) {
        // request login userInfo
        store.dispatch('getUserInfo').then(res => {
          const roles = res.result && res.result.roles
          store.dispatch('GenerateRoutes', { roles }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            router.addRoutes(store.state.permission.addRouters)
            /**
             * 404 页面放到最后进行动态添加
             */
            router.addRoutes(otherRouter)
            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
        })
          .catch((error) => {
            console.error(error)
            Message.error({
              message: '错误',
              description: '请求用户信息失败，请重试'
            })
            // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
            store.dispatch('handleLogOut').then(() => {
              next({ path: loginRoutePath, query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      iView.LoadingBar.finish() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
